package cn.net.xyan.tts.controller;

import cn.net.xyan.tts.api.ISynthesizer;
import cn.net.xyan.tts.utils.AudioUtils;
import cn.net.xyan.tts.utils.TTSFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sound.sampled.AudioInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;


/**
 * Created by zarra on 2017/2/4.
 */
@Controller
@RequestMapping("")
public class TTSController {

    @RequestMapping(value = "/speak")
    @ResponseBody
    public HttpEntity<byte[]> speak(@RequestParam("word")String word
            ,@RequestParam(value="rate",required = false)Integer rate,@RequestParam(value = "volume",required = false)Integer volume) throws IOException {

        if (word == null) throw new NullPointerException();

        if (rate == null) rate = 0;
        if (volume == null) volume =50;

        MediaType wavType = MediaType.parseMediaType("audio/mp3");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(wavType);

        String filename= word+".mp3";

        headers.setContentDispositionFormData("attachment", filename, Charset.forName("UTF-8"));


        ISynthesizer synthesizer = TTSFactory.createISynthesizer();

        synthesizer.setVolume(volume);
        synthesizer.setRate(rate);

        synthesizer.speak(word,null);

        AudioInputStream audioStream = synthesizer.audioStream();

        ByteArrayOutputStream out = new ByteArrayOutputStream();

        AudioUtils.saveMp3Audio(out,audioStream);

        ResponseEntity<byte[]> re = new ResponseEntity<byte[]>(out.toByteArray(),
                headers, HttpStatus.OK);
        return re;
    }
}
